package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Transaction;
import cn.edu.tju.core.model.VirtualWallet;
import cn.edu.tju.core.utils.HttpResult;
import cn.edu.tju.elm.service.WalletService;
import cn.edu.tju.elm.vo.WalletVO.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;


@RestController
@RequestMapping("/api/v1")
public class WalletController {

    @Autowired
    private WalletService walletService;

    // 钱包资源 
    
    /**
     * 创建钱包
     * POST /api/v1/wallets
     */
    @PostMapping("/wallets")
    public HttpResult createWallet(HttpSession session, @RequestBody CreateWalletRequest request) {
        try {
            Integer userId = getUserId(session);
            VirtualWallet wallet = walletService.createWallet(userId, request.getIsVip());
            return HttpResult.success("钱包创建成功", wallet);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户钱包信息
     * GET /api/v1/wallets/me
     */
    @GetMapping("/wallets/me")
    public HttpResult getMyWallet(HttpSession session) {
        try {
            Integer userId = getUserId(session);
            VirtualWallet wallet = walletService.getBalance(userId);
            
            WalletBalanceVO balanceVO = buildBalanceVO(wallet);
            return HttpResult.success("查询成功", balanceVO);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 获取指定用户钱包（管理员功能）
     * GET /api/v1/wallets/{userId}
     */
    @GetMapping("/wallets/{userId}")
    public HttpResult getWallet(@PathVariable Integer userId) {
        try {
            VirtualWallet wallet = walletService.getBalance(userId);
            WalletBalanceVO balanceVO = buildBalanceVO(wallet);
            return HttpResult.success("查询成功", balanceVO);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 更新钱包透支额度
     * PATCH /api/v1/wallets/me/credit-limit
     */
    @PatchMapping("/wallets/me/credit-limit")
    public HttpResult updateCreditLimit(HttpSession session, @RequestBody CreditLimitRequest request) {
        try {
            Integer userId = getUserId(session);
            validateCreditLimit(request.getCreditLimit());
            
            walletService.setCreditLimit(userId, request.getCreditLimit());
            return HttpResult.success("透支额度设置成功");
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    //  交易资源 

    /**
     * 创建充值交易
     * POST /api/v1/wallets/me/transactions
     * body: { "type": "RECHARGE", "amount": 100 }
     */
    @PostMapping("/wallets/me/transactions")
    public HttpResult createTransaction(HttpSession session, @RequestBody TransactionRequest request) {
        try {
            Integer userId = getUserId(session);
            validateAmount(request.getAmount());
            
            Transaction transaction = null;
            
            switch (request.getType()) {
                case "RECHARGE":
                    transaction = walletService.recharge(userId, request.getAmount());
                    break;
                case "WITHDRAW":
                    transaction = walletService.withdraw(userId, request.getAmount());
                    break;
                case "PAYMENT":
                    if (request.getToUserId() == null) {
                        return HttpResult.error("收款用户ID不能为空");
                    }
                    walletService.payment(userId, request.getToUserId(), 
                                         request.getAmount(), request.getOrderId());
                    break;
                default:
                    return HttpResult.error("不支持的交易类型");
            }
            
            return HttpResult.success("交易成功", transaction);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 获取交易流水列表
     * GET /api/v1/wallets/me/transactions?page=1&pageSize=20&type=RECHARGE
     */
    @GetMapping("/wallets/me/transactions")
    public HttpResult getTransactions(HttpSession session,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer pageSize,
                                     @RequestParam(required = false) String type) {
        try {
            Integer userId = getUserId(session);
            List<Transaction> transactions = walletService.getTransactions(userId, page, pageSize);
            
            // 如果指定了类型，可以在Service层过滤
            return HttpResult.success("查询成功", transactions);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 获取单笔交易详情
     * GET /api/v1/wallets/me/transactions/{transactionId}
     */
    @GetMapping("/wallets/me/transactions/{transactionId}")
    public HttpResult getTransaction(HttpSession session, @PathVariable Long transactionId) {
        try {
            Integer userId = getUserId(session);
            Transaction transaction = walletService.getTransactionById(userId, transactionId);
            return HttpResult.success("查询成功", transaction);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    //  冻结资源（子资源）
    
    /**
     * 创建冻结记录
     * POST /api/v1/wallets/me/frozen-amounts
     * body: { "amount": 100, "orderId": 12345 }
     */
    @PostMapping("/wallets/me/frozen-amounts")
    public HttpResult createFrozenAmount(HttpSession session, @RequestBody FreezeRequest request) {
        try {
            Integer userId = getUserId(session);
            validateAmount(request.getAmount());
            
            Transaction transaction = walletService.freezeAmount(
                userId, request.getAmount(), request.getOrderId());
            return HttpResult.success("冻结成功", transaction);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 删除冻结记录（解冻）
     * DELETE /api/v1/wallets/me/frozen-amounts/{orderId}
     */
    @DeleteMapping("/wallets/me/frozen-amounts/{orderId}")
    public HttpResult deleteFrozenAmount(HttpSession session, 
                                        @PathVariable Long orderId,
                                        @RequestBody UnfreezeRequest request) {
        try {
            Integer userId = getUserId(session);
            validateAmount(request.getAmount());
            
            Transaction transaction = walletService.unfreezeAmount(
                userId, request.getAmount(), orderId);
            return HttpResult.success("解冻成功", transaction);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    /**
     * 获取冻结金额列表
     * GET /api/v1/wallets/me/frozen-amounts
     */
    @GetMapping("/wallets/me/frozen-amounts")
    public HttpResult getFrozenAmounts(HttpSession session) {
        try {
            Integer userId = getUserId(session);
            List<Transaction> frozenTransactions = walletService.getFrozenTransactions(userId);
            return HttpResult.success("查询成功", frozenTransactions);
        } catch (Exception e) {
            return HttpResult.error(e.getMessage());
        }
    }

    //  辅助方法 
    
    private Integer getUserId(HttpSession session) {
        //Integer userId = (Integer) session.getAttribute("user_id");
        //if (userId == null) {
        //    throw new RuntimeException("请先登录");
        //}
        //return userId;
        return 12;
       }

    private void validateAmount(BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("金额必须大于0");
        }
    
    }

    private void validateCreditLimit(BigDecimal creditLimit) {
        if (creditLimit == null || creditLimit.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("透支额度必须大于等于0");
        }
    }

    private WalletBalanceVO buildBalanceVO(VirtualWallet wallet) {
        WalletBalanceVO vo = new WalletBalanceVO();
        vo.setBalance(wallet.getBalance());
        vo.setFrozenAmount(wallet.getFrozenAmount());
        vo.setTotalAssets(wallet.getTotalAssets());
        vo.setAvailableAmount(wallet.getAvailableAmount());
        vo.setCreditLimit(wallet.getCreditLimit());
        vo.setOverdraftAmount(wallet.getOverdraftAmount());
        vo.setBonusAmount(wallet.getBonusAmount());
        vo.setIsVip(wallet.getIsVip() == 1);
        return vo;
    }
}

//  VO类 

class TransactionRequest {
    private String type;  // RECHARGE, WITHDRAW, PAYMENT
    private BigDecimal amount;
    private Integer toUserId;  // 用于PAYMENT
    private Long orderId;      // 用于PAYMENT
    
    // getters and setters
    public String getType() { return type; }
    public void setType(String type) { this.type = type; }
    public BigDecimal getAmount() { return amount; }
    public void setAmount(BigDecimal amount) { this.amount = amount; }
    public Integer getToUserId() { return toUserId; }
    public void setToUserId(Integer toUserId) { this.toUserId = toUserId; }
    public Long getOrderId() { return orderId; }
    public void setOrderId(Long orderId) { this.orderId = orderId; }
}